package thread.java20230105;

/**
 * 三个线程交替打印ABC
 */
public class Demo34 {
    static Object locker = new Object();
    static volatile int COUNTER = 0;
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            while (true){
                synchronized (locker){
                    while (COUNTER % 3 ==0){
                        System.out.println("A");
                        COUNTER ++;
                        locker.notifyAll();
                    }
                    //如果唤醒之后, 不满足条件, 要继续等待
                    try {
                        locker.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        });

        Thread t2 = new Thread(()->{
            while (true){
                synchronized (locker){
                    while (COUNTER % 3 ==1){
                        System.out.println("B");
                        COUNTER ++;
                        locker.notifyAll();
                    }
                    //如果唤醒之后, 不满足条件, 要继续等待
                    try {
                        locker.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        Thread t3 = new Thread(()->{
            while (true){
                synchronized (locker){
                    while (COUNTER % 3 ==2){
                        System.out.println("C");
                        COUNTER ++;
                        locker.notifyAll();
                    }
                    //如果唤醒之后, 不满足条件, 要继续等待
                    try {
                        locker.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
